package com.facebook.fresco.samples.showcase.drawee;

import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.fresco.samples.showcase.ResourceTable;
import com.facebook.fresco.samples.showcase.ShowcaseApplication;
import com.zhihu.matisse.library.Matisse;
import com.zhihu.matisse.library.MatisseAbility;
import com.zhihu.matisse.library.MimeType;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.bundle.IBundleManager;
import ohos.utils.net.Uri;

import java.util.ArrayList;

public class DraweeMediaPickerAbility extends Ability {
    public static final String TAG = DraweeMediaPickerAbility.class.getSimpleName();
    private static final int PERMISSION_REQUEST_READ_EXTERNAL_STORAGE = 0;
    private static final Uri ASSERT_URI = Uri.parse("ohos.assets:///resources/rawfile/fresco_logo.png"); //or just: resources/rawfile/huawei_logo.png
    private static final Uri RESOURCE_URI = Uri.parse("ohos.resources://" + ShowcaseApplication.instance.getBundleName() + "/" + ResourceTable.Media_icon);
    private static final int REQUEST_CODE_PICK_MEDIA = 1;
    private SimpleDraweeView mSimpleDraweeView;
    private Text mImagePath;
    private static final int REQUEST_CODE = 23;
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 23;

    private String permissions[] = new String[]{"ohos.permission.READ_MEDIA", "ohos.permission.WRITE_MEDIA", "ohos.permission.CAMERA"};

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(com.facebook.fresco.samples.showcase.ResourceTable.Layout_layout_drawee_media_picker);
        findviews();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
        mSimpleDraweeView.invalidate();
    }

    private void findviews() {
        mSimpleDraweeView = (SimpleDraweeView) findComponentById(ResourceTable.Id_drawee_view);
        mImagePath = (Text) findComponentById(ResourceTable.Id_image_path);
        Component actionOpenDocumentButton = findComponentById(ResourceTable.Id_pick_action_open_document);
        actionOpenDocumentButton.setClickedListener(view-> checkPermission() );

        Component btSetRawFile = findComponentById(ResourceTable.Id_bt_set_raw_file);
        btSetRawFile.setClickedListener(view -> {
            mSimpleDraweeView.setImageURI(ASSERT_URI);
            mImagePath.setText(ASSERT_URI.toString());
        });

        Component btSetResourceFile = findComponentById(ResourceTable.Id_bt_set_resource_file);
        btSetResourceFile.setClickedListener(view -> {
            mSimpleDraweeView.setImageURI(RESOURCE_URI);
            mImagePath.setText(RESOURCE_URI.toString());
        });
    }

    private void checkPermission() {
        if (verifySelfPermission(permissions[0]) != IBundleManager.PERMISSION_GRANTED ||
                        verifySelfPermission(permissions[1]) != IBundleManager.PERMISSION_GRANTED ||
                        verifySelfPermission(permissions[2]) != IBundleManager.PERMISSION_GRANTED) {
            if (canRequestPermission(permissions[0])
                    && canRequestPermission(permissions[1])
                    && canRequestPermission(permissions[2])) {
                requestPermissionsFromUser(
                        permissions, MY_PERMISSIONS_REQUEST_CAMERA);
            }
        } else {
            openGallery();
        }
    }

    private void openGallery() {
        Matisse.from(this)
                .choose(MimeType.of(MimeType.GIF), false)
                .showSingleMediaType(true)
                .countable(true)
                .capture(true)
                .maxSelectable(1)
                .originalEnable(false)
                .forResult(REQUEST_CODE_PICK_MEDIA);
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsFromUserResult(requestCode, permissions, grantResults);
        if(requestCode == MY_PERMISSIONS_REQUEST_CAMERA){
            for (int i = 0; i < grantResults.length; i++) {
                if(grantResults[i] != IBundleManager.PERMISSION_GRANTED){
                    return;
                }
            }
            openGallery();
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (resultCode != MatisseAbility.RESULT_OK) {
            return;
        }
        try {
            ArrayList<Uri> uriArrayList = resultData.getParcelableArrayListParam(MatisseAbility.EXTRA_RESULT_SELECTION);
            if (uriArrayList == null || uriArrayList.isEmpty()) {
                return;
            }
            uriArrayList.forEach(uri -> {
                mSimpleDraweeView.setImageURI(uri);  // dataability:///media/external/images/media/133
                mImagePath.setText(uri.toString());
            });
        }catch (Exception e){
            //ignore
        }
    }
}
